import os
import re
import shlex
from rif import RIFXml

class App:
    def __init__(self):
        self.cmd = [s.strip() for s in open("cmd", "r").readlines()]
        dbs = [x for x in os.listdir("..") if re.match('renjunet.*?\.rif', x)]
        if len(dbs) == 0:
            raise Exception("no source db")

        self.main = RIFXml("../database.rif")
        self.main.load()
        self.dbs = dbs

        self.aux = None
        
    def loadAux(self):
        if self.aux == None:
            self.aux = RIFXml("../" + self.dbs[-1])
            self.aux.load()
    
    def run(self):
        for cmd in self.cmd:
            seq = shlex.split(cmd)
            if len(seq) == 0:
                continue
            if seq[0] == ';':
                continue
            if seq[0] == "copy-tournament":
                self.loadAux()
                self.main.copyTournament(seq[1], self.aux)
                continue
            if seq[0] == "show-diff":
                self.loadAux()
                self.main.showDiff(seq[1], self.aux)
                continue
            if seq[0] == "delete-tournament":
                self.main.deleteTournament(seq[1])
                continue
            if seq[0] == "delete-game":
                self.main.deleteGame(seq[1])
                continue
            if seq[0] == "add-game":
                self.main.addGame(seq[1], seq[2],seq[3], seq[4], seq[5])
            if seq[0] == "fix-game-player":
                self.main.fixGamePlayer(seq[1], seq[2], seq[3])
            if seq[0] == "fix-player":
                self.main.fixPlayer(seq[1], seq[2])
            if seq[0] == "new-tournament":
                self.main.newTournament(seq[1], seq[2], seq[3])
        self.main.save("../database-" + self.main.date + ".rif")
    
    
app = App()
app.run()



